<template>
  <div class="app-container">
    <el-form
      class="filters"
      ref="searchForm"
      :model="searchForm"
      label-width="80px"
    >
      <el-form-item label="用户名">
        <el-input v-model="searchForm.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="searchForm.mobile" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="是否启用">
        <el-select v-model="searchForm.isEnable" placeholder="请选择是否启用">
          <el-option
            v-for="item in enumsJson.IS_ENABLE"
            :key="item.code"
            :label="item.label"
            :value="item.code"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <div class="search-btns">
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-search"
          @click="doSearch"
          >搜索</el-button
        >
        <el-button
          type="default"
          size="mini"
          icon="el-icon-refresh"
          @click="resetSearch"
          >重置</el-button
        >
      </div>
    </el-form>
    <div class="searchs-content">
      <el-button
        type="primary"
        size="mini"
        plain
        icon="el-icon-plus"
        @click="addDialog"
        >新增</el-button
      >
    </div>
    <Table
      :tableHeader="tableHeader"
      :tableData="tableData"
      :tableLoading="listLoading"
    >
      <template slot="isEnable" slot-scope="scope">
        <el-switch
          v-model="scope.row.isEnable"
          :active-value="1"
          :inactive-value="0"
          @change="isEnableChange($event, scope.row)"
        >
        </el-switch>
      </template>
      <template slot="action" slot-scope="scope">
        <!-- 管理员账号不可编辑，禁用账号不可操作 -->
        <el-button
          type="primary"
          size="mini"
          @click="addDialog(scope.row)"
          v-if="
            scope.row.id != 1 &&
            scope.row.isEnable !== 0
          "
          >编辑</el-button
        >
        <el-button
          type="success"
          size="mini"
          @click="isSetMenuRow(scope.row)"
          v-if="
            scope.row.id != 1 &&
            scope.row.isEnable !== 0
          "
          >菜单分配</el-button
        >
      </template>
    </Table>
    <pagination
      v-if="total > 0"
      :total="total"
      :page.sync="searchForm.pageNum"
      :limit.sync="searchForm.pageSize"
      :pageSizes="[15, 30, 45, 50]"
      @pagination="fetchData"
    />

    <!-- 弹框 -->
    <Dialog
      :visible="visible"
      width="35%"
      :isFooter="false"
      :title="dialogTitle + '人员'"
      @cancelDialog="cancelDialog"
    >
      <AddUser :currentRow="currentRow" @cancelDialog="cancelDialog"></AddUser>
    </Dialog>

    <!-- 分配菜单弹框 -->
    <Dialog
      :visible="menuVisible"
      width="35%"
      :loading="dialogBtnLoading"
      title="菜单分配"
      @confirmDialog="confirmMenuDialog"
      @cancelDialog="cancelMenuDialog"
    >
      <div class="menu-title">升级平台权限</div>
      <el-checkbox
        class="allcheckbox"
        v-model="checkedChoose"
        @change="chooseAll"
        >全选/全不选</el-checkbox
      >
      <el-tree
        class="menu-tree"
        ref="menuTree"
        :data="treeData"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="treeMenuIds"
        :props="defaultProps"
        :filter-node-method="filterNode"
        @check="handleTree"
      >
      </el-tree>
    </Dialog>
  </div>
</template>

<script>
import { userManage } from "@/api/system";
import { getMenu } from "@/api/user";
import { users } from "@/api/login";

import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import Table from "@/components/Table";
import Dialog from "@/components/Dialog";
import AddUser from "./addUser.vue";

import { handleConfirm } from "@/utils/messageBox";

import { removeNullUndefined } from "@/utils/index.js";
import { mapState } from "vuex";

export default {
  name: "User",
  components: { Pagination, Table, Dialog, AddUser },

  data() {
    return {
      listLoading: false,
      total: 0,
      searchForm: {
        pageNum: 1,
        pageSize: 15,
        username: "",
        mobile: "",
        isEnable: "",
      },

      tableHeader: [
        {
          type: "index",
          label: "序号",
          width: "60",
          fixed: true,
        },
        {
          label: "手机号",
          prop: "mobile",
        },
        {
          label: "用户名",
          prop: "username",
        },
        {
          label: "是否启用",
          slot: "isEnable",
        },
        { slot: "action", label: "操作" },
      ],
      tableData: [],
      visible: false, //弹框标识
      dialogForm: {
        userName: "",
        loginName: "",
        password: "123456",
        phone: "",
      },
      dialogTitle: "",

      currentRow: {},
      checkedChoose: false,
      treeData: [],
      treeMenuIds: [],
      menuVisible: false,
      dialogBtnLoading: false,
      defaultProps: {
        children: "children",
        label: "name",
        disabled: "isInner",
      },
    };
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
      enumsJson: (state) => state.enums.enums,
    }),
  },

  created() {
    this.fetchData();
    this.getMenuList();
  },
  methods: {
    fetchData(val) {
      this.searchForm.pageNum = val ? val.page : this.searchForm.pageNum;

      this.listLoading = true;
      this.tableData = [];
      this.total = 0;
      userManage(
        "/list",
        "post",
        {
          ...removeNullUndefined(this.searchForm),
        },
        1
      )
        .then((res) => {
          this.tableData = res.data;
          this.total = +res.total;
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
    // 弹框取消
    cancelDialog(type) {
      this.visible = false;
      if (type) this.fetchData();
    },

    // 新增
    addDialog(row) {
      this.visible = true;
      this.currentRow = {};
      if (row.id) {
        this.dialogTitle = "编辑";
        this.currentRow = row;
      } else {
        this.dialogTitle = "新增";
      }
    },
    submitDialogForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
        } else {
          return false;
        }
      });
    },
    resetDialogForm(formName) {
      this.$refs[formName].resetFields();
    },

    // 搜索重置
    resetSearch() {
      this.searchForm = {
        pageNum: this.searchForm.pageNum,
        pageSize: this.searchForm.pageSize,
        username: "",
        mobile: "",
        isEnable: "",
      };
    },
    doSearch() {
      this.searchForm.pageNum = 1;
      this.fetchData();
    },
    isEnableChange(e, row) {
      if (e == 1) {
        row.isEnable = 0;
      } else {
        row.isEnable = 1;
      }
      if (row.id == 1) {
        this.$message.warning("管理员账号不可操作！");
        return;
      }
      handleConfirm(
        `确定要${row.isEnable == 1 ? "禁用" : "启用"}该用户吗？`,
        "warning",
        "提示"
      )
        .then((res) => {
          this.doEnableUser(row);
        })
        .catch((err) => {});
    },
    doEnableUser(row) {
      userManage(
        "/update/enable",
        "post",
        { id: row.id, isEnable: row.isEnable == 1 ? 0 : 1 },
        1
      ).then((res) => {
        if (res.code == 200) {
          this.$message.success(res.message);
          this.fetchData();
        }
      });
    },
    isSetMenuRow(row) {
      this.currentRow = row;
      this.menuVisible = true;

      this.getUserMenu(row);
    },
    // 获取用户菜单权限
    async getUserMenu(row) {
      const menus = await getMenu(`/ids/${row.id}`, "post");
      menus.data &&
        menus.data.map((item) => {
          let node = this.$refs.menuTree.getNode(item);
          if (node && node.isLeaf) {
            this.$refs.menuTree.setChecked(node, true);
          }
        });
      this.treeMenuIds = this.$refs.menuTree.getCheckedKeys();
    },
    handleTree(nodeObj, SelectedObj) {
      this.treeMenuIds = SelectedObj.checkedKeys;
    },
    // 弹框取消
    cancelMenuDialog() {
      this.menuVisible = false;
      this.$nextTick(() => {
        //Dom更新完毕
        this.$refs.menuTree.setCheckedKeys([]);
      });
      this.checkedChoose = false;
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) != -1;
    },
    // 全部选中
    chooseAll() {
      this.treeMenuIds = [];
      // 判断按钮的状态
      if (this.checkedChoose) {
        // 设置
        this.$refs.menuTree.setCheckedNodes(this.treeData, true, true);
        for (var i = 0; i < this.$refs.menuTree.getCheckedNodes().length; i++) {
          this.treeMenuIds.push(this.$refs.menuTree.getCheckedNodes()[i].id);
        }
      } else {
        this.$refs.menuTree.setCheckedNodes([]);
        this.treeMenuIds = [];
      }
    },
    async getMenuList() {
      let data = await getMenu("/tree", "get");
      this.treeData = data.data;
    },
    confirmMenuDialog() {
      handleConfirm(`确定要给该人员分配菜单权限吗？`, "warning", "提示")
        .then((res) => {
          this.doOperate();
        })
        .catch((err) => {});
    },
    doOperate() {
      this.dialogBtnLoading = true;

      // 获取选中级/半选中
      let parentIds = this.$refs.menuTree.getHalfCheckedKeys();
      let childsIds = this.$refs.menuTree.getCheckedKeys();
      // 利用set没有重复的值这一特性, 实现数组去重。Array.form方法可以将 Set 结构转为数组。
      let treeMenuIds = Array.from(new Set(parentIds.concat(childsIds)));

      users("/update/menus", "post", 1, {
        menuIds: treeMenuIds,
        userId: this.currentRow.id,
      })
        .then((res) => {
          if (res.code == 200) {
            this.$message.success(res.message);
            this.menuVisible = false;
            this.fetchData();
          }
        })
        .finally(() => {
          this.dialogBtnLoading = false;
        });
    },
  },
};
</script>
<style lang="scss">
.el-cascader-panel {
  .el-scrollbar:first-child {
    .el-checkbox {
      display: none;
    }
  }
}

.el-tree-node.is-current > .el-tree-node__content {
  color: #fff;
  background: #5473e8;
}

.el-tree-node {
  margin-top: 8px;
}
</style>
<style lang="scss" scoped>
.filter-tree {
  height: 78vh;
  overflow: auto;
  margin-top: 12px;
}

.el-select,
.el-cascader {
  width: 80%;
}

.clear-permission-btn {
  margin: -10px 0 20px 0;
}
.allcheckbox {
  ::v-deep .el-checkbox__label {
    font-size: 16px;
    color: #333333;
  }
  ::v-deep .el-checkbox__inner {
    width: 17px;
    height: 17px;
  }
}
.menu-title {
  text-align: center;
  margin-top: -0.7rem;
  font-size: 16px;
  font-weight: 500;
}
::v-deep .dialog-container .el-dialog__body {
  min-height: auto;
}
</style>
